import {uSelectMyDevListByUserId} from '@/api'
import {getStorage} from '@/utils/localstoreage'
import {
  Button,
  CommonEventFunction,
  Picker,
  PickerSelectorProps,
  View,
  Text
} from '@tarojs/components'
import {useEffect, useState} from 'react'

const DevPicker: React.FC<{
  onChange: (dev: SimpleDeviceData | undefined) => void
}> = ({onChange}): JSX.Element => {
  const [simpleDevList, setSimpleDevList] = useState<SimpleDeviceData[]>([])

  const [rangeIndex, setRangeIndex] = useState<number | undefined>(undefined)

  const handleDevPickerChange: CommonEventFunction<
    PickerSelectorProps.ChangeEventDetail
  > = e => {
    let index = Number(e.detail.value)
    setRangeIndex(index)
    let dev = simpleDevList[index]
    onChange(dev)
  }

  function updateDataSource() {
    let userId = getStorage('userId')
    if (!userId) return
    uSelectMyDevListByUserId({userId})
      .then(res => {
        setSimpleDevList(res.data)
        setRangeIndex(undefined)
      })
      .catch(err => {
        setSimpleDevList([])
        setRangeIndex(undefined)
      })
  }

  useEffect(() => {
    updateDataSource()
  }, [])

  return (
    <View className="w-full h-full flex items-center gap-x-16 px-8 rounded-8 border-solid border-1 border-xx_line">
      <Picker
        className="flex-1 h-full bg-white rounded-4 flex justify-center items-center"
        range={simpleDevList}
        rangeKey={'devName'}
        value={rangeIndex}
        onChange={handleDevPickerChange}
      >
        <View className="text-14 text-xx_text">
          {rangeIndex === undefined
            ? '选择设备'
            : simpleDevList[rangeIndex].devName}
        </View>
      </Picker>
      {rangeIndex !== undefined ? (
        <Button
          size="mini"
          className="text-14 text-xx_text bg-primary_half text-white"
          onClick={() => {
            onChange(undefined)
            setRangeIndex(undefined)
          }}
        >
          <Text className="text-white">清空</Text>
        </Button>
      ) : null}
    </View>
  )
}
export default DevPicker
